package com.aruba.paging3application.paging

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.aruba.flowapplyapplication.net.Api
import com.aruba.flowapplyapplication.net.RetrofitClient
import com.aruba.paging3application.entity.Movie
import com.aruba.paging3application.entity.Movies
import kotlinx.coroutines.delay

/**
 * Pagind获取数据层
 * Created by aruba on 2021/9/22.
 */
class MoviePagingSource : PagingSource<Int, Movie>() {
    companion object {
        const val pageSize = 10
    }

    //该办法只在初始加载成功且加载页面的列表不为空的情况下被调用。
    override fun getRefreshKey(state: PagingState<Int, Movie>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Movie> {
        val currentPage = params.key ?: 1
        val movies = RetrofitClient.getApi(Api::class.java).getMovies(currentPage, pageSize)

        //上一页的key
        val prevKey: Int? = (currentPage - 1).run {
            if (this == 0) {//说明当前是第一页数据
                null
            } else {
                this
            }
        }

        //下一页的key
        val nextKey: Int? = when {
            params.loadSize > pageSize -> {//第一次加载的会多一些
                // public val initialLoadSize: Int = pageSize * DEFAULT_INITIAL_PAGE_MULTIPLIER, 
                // 默认PagingConfig为pager分配初始获取数据的大小为pageSize * DEFAULT_INITIAL_PAGE_MULTIPLIER
                // 所以Pager配置时，如果initialLoadSize不指定，那么第一次加载数据并不是我们定义的pageSize
                val count = params.loadSize / pageSize
                count + 1
            }
            movies.hasMore -> {
                currentPage + 1
            }
            else -> {
                null
            }
        }

        return LoadResult.Page(
            data = movies.movies,
            prevKey = prevKey,
            nextKey = nextKey
        )
    }
}